package com.bicon.botu.mall.order.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.order.common.OrderConstans;
import com.bicon.botu.mall.order.dto.CustomerStatisticsDTO;
import com.bicon.botu.mall.order.dto.OrderGoodsAfterSalesDto;
import com.bicon.botu.mall.order.dto.OrderGoodsAndAddressDto;
import com.bicon.botu.mall.order.dto.TotalPriceDTO;
import com.bicon.botu.mall.order.entity.OrderGoods;
import com.bicon.botu.mall.order.service.IOrderChildService;
import com.bicon.botu.mall.order.service.IOrderGoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 组合订单 后台控器
 *
 * @Author dsp
 * @Date 2018-05-14
 */
@RestController
@RequestMapping(value = "/V3.0.0/order-goods")
public class OrderGoodsController extends BaseController {

    @Autowired
    private IOrderGoodsService iOrderGoodsService;

    @Autowired
    private IOrderChildService iOrderChildService;

    /**
     * 修改
     *
     * @param orderGoods
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseResult update(OrderGoods orderGoods) {
        //传参数校验
        if (orderGoods != null && StringUtils.isNoneBlank(orderGoods.getId())) {
            boolean result = iOrderGoodsService.updateById(orderGoods);
            if (result) {
                if (null != orderGoods.getBuyerMessage()) {
                    List<OrderGoods> list = new OrderGoods().selectList(new EntityWrapper<OrderGoods>()
                            .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("id", orderGoods.getId()));
                    String remark = "修改订单备注";
                    iOrderChildService.insertOrderRecord(getUserId(), list, remark);
                }
                if (null != orderGoods.getPayState()){
                    List<OrderGoods> list = new OrderGoods().selectList(new EntityWrapper<OrderGoods>()
                            .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("id", orderGoods.getId()));
                    String remark = "交易关闭";
                    iOrderChildService.insertOrderRecord(getUserId(), list, remark);
                }
                return sendResult200();
            } else {
                return sendResult(OrderConstans.RESPONSE_CODE_600, OrderConstans.RESPONSE_MESSAGE_600);
            }
        } else {
            return sendResult400();
        }
    }

    /**
     * 订单列表分页
     *
     * @param type
     * @param keyWord
     * @param sortType
     * @param sortDirection
     * @param params
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "getOrderPageByCondition", method = RequestMethod.POST)
    public BaseResult getOrderPageByCondition(@RequestParam(required = false) String type,
                                              @RequestParam(required = false) String keyWord,
                                              @RequestParam(required = false) String sortType,
                                              @RequestParam(required = false) String sortDirection,
                                              @RequestParam Map<String, String> params,
                                              @RequestParam(defaultValue = "0") Integer pageNo,
                                              @RequestParam(defaultValue = "10") Integer pageSize) {
        if (params != null && !params.isEmpty() && params.containsKey("storeId")) {
            if (StringUtils.isNoneBlank(type, keyWord)) {
                params.put(type, keyWord);
            }
            Page<OrderGoodsAndAddressDto> page = new Page<OrderGoodsAndAddressDto>(pageNo, pageSize);
            if (StringUtils.isNotBlank(sortType)) {
                page.setOrderByField(sortType);
                page.setAsc("ASC".equals(sortDirection) ? true : false);
            } else {
                page.setOrderByField("goods_create_date");
                page.setAsc(false);
            }
            Page<OrderGoodsAndAddressDto> resultPage = iOrderGoodsService.getOrderPageByCondition(page, params);
            return sendResult200(resultPage);
        } else {
            return sendResult400();
        }
    }

    /**
     * 订单详情页 修改运费及优惠费
     *
     * @param discountMoney
     * @param freight
     * @return
     */
    @RequestMapping(value = "updateCost", method = RequestMethod.POST)
    public BaseResult updateCost(String orderGoodsId, Double discountMoney, Double freight) {
        if (StringUtils.isNotBlank(orderGoodsId) && (discountMoney != null || freight != null)) {
            if (iOrderGoodsService.updateCost(orderGoodsId, discountMoney, freight,getUserId())) {
                return sendResult200();
            } else {
                return sendResult(OrderConstans.RESPONSE_CODE_600, OrderConstans.RESPONSE_MESSAGE_600);
            }
        } else {
            return sendResult400();
        }
    }

    /**
     * 根据商家ID 统计订单总数、待付款、待收货等状态对应数量
     *
     * @param storeId
     * @param payStateArray
     * @return
     */
    @RequestMapping(value = "getOrderTotalByStoreId", method = RequestMethod.POST)
    public BaseResult getOrderTotalByStoreId(String storeId, @RequestParam(required = false) List<String> payStateArray) {
        //参数校验
        if (StringUtils.isNotBlank(storeId)) {
            List<TotalPriceDTO> priceDTOList = iOrderGoodsService.getOrderTotalByStoreId(storeId, payStateArray);
            return sendResult200(priceDTOList);
        } else {
            return sendResult400();
        }
    }

    /**
     * 根据商家ID 统计提醒订单总数、待付款、待收货等状态对应数量
     *
     * @param storeId
     * @return
     */
    @RequestMapping(value = "getWarnOrderTotalByStoreId", method = RequestMethod.POST)
    public BaseResult getWarnOrderTotalByStoreId(String storeId) {
        List<TotalPriceDTO> priceDTOList = iOrderGoodsService.getWarnOrderTotalByStoreId(storeId);
        return sendResult200(priceDTOList);
    }

    /**
     * 商城管理后台-订单管理-订单列表-批量发货功能
     * @param orderGoodsIds 订单ID字符串
     * @return
     */
    @RequestMapping(value = "gatchDeliverGoods", method = RequestMethod.POST)
    public BaseResult gatchDeliverGoods(String orderGoodsIds){
        //参数校验
        if (StringUtils.isNotBlank(orderGoodsIds)){
            List<String> stringList= Arrays.asList(StringUtils.split(orderGoodsIds,","));
            if (stringList.size()>0){
                return sendResult200(iOrderGoodsService.getOrderGoodsAndAddressByIds(stringList));
            } else {
                return sendResult400();
            }
        }else{
            return sendResult400();
        }
    }


    /**
     * 商城管理后台-订单管理-订单列表-打印快递单功能
     * @param orderGoodsIds 订单ID字符串
     * @return
     */
    @RequestMapping(value ="gatPrintTrackingInfo",method = RequestMethod.POST)
    public BaseResult gatPrintTrackingInfo(String orderGoodsIds){
        //参数校验
        if (StringUtils.isNotBlank(orderGoodsIds)){
            List<String> stringList= Arrays.asList(StringUtils.split(orderGoodsIds,","));
            if (stringList.size()>0){
                return sendResult200(iOrderGoodsService.gatPrintTrackingInfo(stringList));
            }else{
                return sendResult400();
            }
        }else{
            return sendResult400();
        }
    }

    @RequestMapping(value = "/exportOrder", method = RequestMethod.GET)
    public void exportOrder(@RequestParam(required = false) String type,
                                          @RequestParam(required = false) String keyWord,
                                          @RequestParam(required = false) String sortType,
                                          @RequestParam(required = false) String sortDirection,
                                          @RequestParam Map<String,String> params,
                                          HttpServletRequest request,
                                          HttpServletResponse response){
        if (params != null && !params.isEmpty() && params.containsKey("storeId")) {
            if (StringUtils.isNoneBlank(type, keyWord)) {
                params.put(type, keyWord);
            }
            if (StringUtils.isBlank(sortType)) {
                sortType = "goods_create_date";
                sortDirection = "DESC";
            }
            String url = iOrderGoodsService.exportOrder(params, sortType, sortDirection,request,response);
        } else {
            throw new BusinessException(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400);
        }
    }

    /**
     * 顾客支付后统计
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value ="customers-statistics",method = RequestMethod.GET)
    public BaseResult customersStatistics(@RequestParam(required = false) String startTime,@RequestParam(required = false) String endTime){
        List<CustomerStatisticsDTO> list = iOrderGoodsService.customersStatistics(startTime,endTime);
        return sendResult200(list);
    }


    /**
     * 订单统计
     * @param type
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value ="order-statistics",method = RequestMethod.GET)
    public BaseResult orderStatistics(@RequestParam Integer type,@RequestParam String startTime,@RequestParam String endTime){
        List<CustomerStatisticsDTO> list = null;
        if(type==1){
            //支付成功的订单数量
            list = iOrderGoodsService.paidStatistics(startTime,endTime);
        }else if(type==2){
            //支付成功的订单总额
            list = iOrderGoodsService.paidMoneyStatistics(startTime,endTime);
        }else if(type==3){
            //交易成功的订单数量
            list = iOrderGoodsService.doneOrderStatistics(startTime,endTime);
        }else{
            //交易成功的订单总额
            list = iOrderGoodsService.doneOrderMoneyStatistics(startTime,endTime);
        }
        return sendResult200(list);
    }


    @RequestMapping(value ="/after-sales",method = RequestMethod.GET)
    public BaseResult<List<OrderGoodsAfterSalesDto>> queryOrderGoodsAfterSales(@RequestParam String orderGoodsId,@RequestParam(value = "type",required = false,defaultValue = "1") Integer type){
        return this.sendResult200(this.iOrderGoodsService.queryOrderGoodsAfterSales(orderGoodsId,type));
    }

}
